﻿using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Contracts.Odyssey;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Entities.Odyssey;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.RC.EAPClient;
using Newtonsoft.Json;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Glorysoft.EAP.RC.Odyssey
{

    public class OdysseyService : AbstractService
    {
        public string Name => GetType().Name;
        public string CurrentMethod => MethodBase.GetCurrentMethod().Name;
        private readonly Logger CimLogger;
        private DbService dbServer = null;
        EAPClientService ClientService = null;
        OdysseyClient odysseyClient = null;

        public OdysseyService()
        {
            dbServer = new DbService();
            CimLogger = XfwContext.LogManager.EapLogger;
            odysseyClient = new OdysseyClient();
        }


        #region 出站发送TrackOut
        /// <summary>
        /// 向Odyssey 发送出站请求
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void TrackOut(XfwArgs xfwArgs)
        {
            try
            {
                var eqpid = Dict.Current.lotInfo.eqptID;
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var message = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpid, MessageType.Info, message, MessageOrigin.MES);
                    xfwArgs.SetReturnCodeNG($"{Name}.TrackOut() The EAP has been switched Automatic Operation");
                    return;
                }
                var lotID = Dict.Current.lotInfo.lotId;
                var userName = Dict.Current.lotInfo.userName;
                var operationId = Dict.Current.lotInfo.operationId;
                xfwArgs.Header[CItems.EqpID] = eqpid;
                xfwArgs.Header[CItems.LotID] = lotID;
                var rptRunHisTemp = dbServer.SeleteRunHsiTemp(eqpid, lotID);
                if (rptRunHisTemp != null)
                {
                    xfwArgs.Header[CItems.TrackOutReturnCode] = "99";
                    xfwArgs.SetReturnCodeNG($"{Name}.TrackOut() eqpid:{eqpid},lotID:{lotID} 已出站或者没有进站信息");
                    return;
                }
                //基本信息
                lotBaseInfo lotbaseInfo = new lotBaseInfo();
                lotbaseInfo.lotId = lotID;
                lotbaseInfo.equipmentId = eqpid;
                lotbaseInfo.operationId = operationId;
                lotbaseInfo.trackFlag = "out";
                var lotbaseInfo_jsonvalue = JsonConvert.SerializeObject(lotbaseInfo);
                //参数信息
                parameterSet parameterset = Dict.Current.parameterSet; ;
                var parameterSet_jsonvalue = JsonConvert.SerializeObject(parameterset);

                var result = odysseyClient.TrackOut(lotbaseInfo_jsonvalue, parameterSet_jsonvalue);
                if (result == null)
                {
                    xfwArgs.Header[CItems.TrackOutReturnCode] = "-1";
                    xfwArgs.SetReturnCodeNG("TrackOut: trackout==null");
                    return;
                }
                else if (result.success.ToUpper() == "FALSE")
                {
                    xfwArgs.Header[CItems.TrackOutReturnCode] = "1";
                    xfwArgs.SetReturnCodeNG("TrackOut: result.success==False");
                    return;
                }
                xfwArgs.Header[CItems.TrackOutReturnCode] = "0";
                //xfwArgs.Header[CItems.LotID] = result.lotId;
                //xfwArgs.Header[CItems.EqpID] = result.equipmentId;
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SaveTest() Execute Error.");
            }
        }
        /// <summary>
        /// 出站结果
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void TrackOutResult(XfwArgs xfwArgs)
        {
            try
            {
                var eqpId = xfwArgs.Header[CItems.EqpID]?.ToString();
                var lotID = xfwArgs.Header[CItems.LotID]?.ToString();
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpId, MessageType.Info, messages, MessageOrigin.ODYSSEY);
                    xfwArgs.SetReturnCodeNG($"{Name}.TrackOutResult() The EAP has been switched Automatic Operation");
                    return;
                }

                var returnCode = xfwArgs.Header[CItems.TrackOutReturnCode]?.ToString();
                if (returnCode == "99")
                {
                    xfwArgs.SetReturnCodeNG($"{Name}.TrackOutResult() eqpid:{eqpId},lotID:{lotID} 已出站或者没有进站信息");
                    return;
                }
                xfwArgs.Header[CItems.MessageOrigin] = MessageOrigin.ODYSSEY.ToString();
                if (returnCode == "0")
                {
                    //MES "TrackOut" 成功，提示Client
                    xfwArgs.Header[CItems.MessageType] = MessageType.Info.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.MESTrackOutOK);
                    xfwArgs.Header[CItems.TerminalMessage] = msgs;
                    var rptRunHisTemp = dbServer.SeleteRunHsiTemp(eqpId, lotID);
                    if (rptRunHisTemp != null)
                    {
                        //if (string.IsNullOrEmpty(rptRunHisTemp.END_TIME))
                        //{
                        //    rptRunHisTemp.END_TIME = DateTime.Now.ToString();
                        //}
                        rptRunHisTemp.TRACKOUT_TIME = DateTime.Now.ToString();
                        dbServer.UpdateRunHsiTempByID(rptRunHisTemp);
                    }
                    CimLogger.Information($"{Name}.TrackOutResult() ：TrackOut 成功.");

                }
                else
                {
                    //MES "TrackOut"失败，提示Client
                    xfwArgs.Header[CItems.MessageType] = MessageType.Error.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.MESTrackOutNG);
                    xfwArgs.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Information($"{Name}.TrackOutResult() ：TrackOut 失败.");
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.TrackOutResult() Execute Error.");
                xfwArgs.SetReturnCodeNG(ex.Message);
            }
        }
        #endregion
    }
}
